
package com.uuah.server.bootstrap.wrapper;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


public class DefaultUuahClassPathConfig {
	protected static final String UUAH_DIR = "/lib/uuah";
	protected static final String USER_DIR = "/lib/user";
	protected static final String OPT_DIR = "/lib/opt";

	private List urls = new ArrayList();

	public DefaultUuahClassPathConfig(File uuahHome, File uuahBase) {
		try {
			if (!uuahHome.getCanonicalFile().equals(uuahBase.getCanonicalFile())) {
				File userOverrideDir = new File(uuahBase, USER_DIR);
				this.addFile(userOverrideDir);
				this.addFiles(this.listJars(userOverrideDir));
			}
		} catch (IOException ioe) {
			System.out
					.println("Unable to check to see if there are local jars to load: "
							+ ioe.toString());
		}

		File userDir = new File(uuahHome, USER_DIR);
		this.addFile(userDir);
		this.addFiles(this.listJars(userDir));

		File uuahDir = new File(uuahHome, UUAH_DIR);
		this.addFile(uuahDir);
		this.addFiles(this.listJars(uuahDir));

		File optDir = new File(uuahHome, OPT_DIR);
		this.addFile(optDir);
		this.addFiles(this.listJars(optDir));
	}

	public List getURLs() {
		return new ArrayList(this.urls);
	}

	public void addURLs(List urls) {
		if (urls != null && !urls.isEmpty()) {
			this.urls.addAll(urls);
		}
	}

	public void addURL(URL url) {
		this.urls.add(url);
	}

	public void addFiles(List files) {
		for (Iterator i = files.iterator(); i.hasNext();) {
			this.addFile((File) i.next());
		}
	}

	public void addFile(File jar) {
		try {
			this.addURL(jar.getAbsoluteFile().toURI().toURL());
		} catch (MalformedURLException mux) {
			throw new RuntimeException("Failed to construct a classpath URL",
					mux);
		}
	}

	protected List listJars(File path) {
		File[] jars = path.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				try {
					return pathname.getCanonicalPath().endsWith(".jar");
				} catch (IOException e) {
					throw new RuntimeException(e.getMessage());
				}
			}
		});

		return jars == null ? Collections.EMPTY_LIST : Arrays.asList(jars);
	}

}
